package java.com.wolfsea.lib_drawable
import android.content.Context
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import com.wolfsea.lib_drawable.R
import java.lang.IllegalArgumentException

/**
 *@desc  两种icon切换的View
 *@author liuliheng
 *@time 2022/2/28  23:59
 **/
class IconsSwitchView : View {

    constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet) {
        init(context, attributeSet)
    }

    constructor(context: Context, attributeSet: AttributeSet?, defaultRes: Int) : super(
        context,
        attributeSet,
        defaultRes
    ) {
        init(context, attributeSet)
    }

    /**
     *@desc 初始化方法
     *@author:liuliheng
     *@time: 2022/3/1 0:07
    **/
    private fun init(context: Context, attributeSet: AttributeSet?) {

        var darkRes: Int
        var brightRes: Int

        context.obtainStyledAttributes(attributeSet, R.styleable.Drawable_Style).apply {
            darkRes = getResourceId(R.styleable.Drawable_Style_darkRes, -1)
            brightRes = getResourceId(R.styleable.Drawable_Style_brightRes, -1)
            recycle()
        }

        if (darkRes != -1 && brightRes != -1) {
            val stateListDrawable = StateListDrawable().apply {
                addState(intArrayOf(android.R.attr.state_selected), context.resources.getDrawable(brightRes))
                addState(intArrayOf(android.R.attr.state_checked), context.resources.getDrawable(brightRes))
                addState(intArrayOf(android.R.attr.state_pressed), context.resources.getDrawable(brightRes))
                addState(intArrayOf(), context.resources.getDrawable(darkRes))
            }
            this.isClickable = true
            this.isFocusable = true
            this.background = stateListDrawable
        } else {
            throw IllegalArgumentException("must set darkRes and brightRes.")
        }
    }

}